<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Config;
use app\common\library\Auth;
use app\admin\model\Car as Car_Model;
use app\admin\model\User as User_Model;
use fast\Http;
use addons\third\library\Service;
/**
 * 个人中心接口
 */
class My extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        $this->token = $this->request->post('token');
        if ($this->request->action() == 'login' && $this->token) {
            $this->request->post(['token' => '']);
        }
        parent::_initialize();
    }  
    

    /**
     * 小程序获取用户授权数据的接口
     * @ApiSummary  (小程序用户授权后把头像和昵称信息储存到数据库)
     * @ApiMethod   (POST)
     * @ApiParams   (name="openid", type="string", required=true, description="微信openid")
     * @ApiParams   (name="rawData", type="string", required=true, description="微信获取的rawData")
     */
    public function miniGetuserinfo()
    {
        $openid = $this->request->post("openid");
        $rawData = $this->request->post("rawData");
        if (!$rawData) {
            $this->error($rawData);
        }

        $rawData = htmlspecialchars_decode($rawData);
        $userInfo = (array)json_decode($rawData, true);
       
        $platform = 'wxapp';
        $result = [
            'openid'        => $openid,
            'userinfo'      => [
                'nickname' => $userInfo['nickName'],
            ],
        ];
        $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
        
        // 第三方登录入库
        $ret = Service::connect($platform, $result, $extend);
        if ($ret) {
            //登录成功后的用户数据操作
            $auth = Auth::instance();

            $this->success("微信授权成功", ['userInfo' => $auth->getUserinfo()]);
        } else {
            $this->error("微信授权失败");
        }
    }

    /**
     * 小程序登录接口
     * @ApiSummary  (小程序登录接口)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信获取的code")
     * @ApiParams   (name="Invitees", type="int", required=false, description="分享人的user_id")
     * @ApiReturnParams   (name="openid", type="string", required=true, description="openid")
     * @ApiReturnParams   (name="http_result", type="string", required=true, description="wx登录返回的数据")
     * @ApiReturnParams   (name="vip_time_status", type="int", required=true, description="如果是VIP返回1 否则返回0")
     * @ApiReturnParams   (name="vip_time", type="string", required=true, description="如果是VIP返回 VIP到期时间")
     */
    public function miniapplogin()
    {
        $config = get_addon_config('third');    
        $config = $config['wechat'];

        $code = $this->request->post("code");
        $Invitees = $this->request->post("Invitees");
        if (!$code) {
            $this->error("参数不正确");
        }
        
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];

        $http_result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');

        if ($http_result['ret']) {
            $json = (array)json_decode($http_result['msg'], true);
            if (isset($json['openid'])) {
                
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'access_token'  => $json['session_key'],
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'Invitees'    => isset($Invitees) ? $Invitees : 0,
                ];
                // 第三方登录入库
                // 在user表创建一条新用户数据
                $ret = Service::connect($platform, $result);
                if ($ret) {
                    //登录成功后的用户数据操作
                    $auth = Auth::instance();

                    $return_user_data = $auth->getUserinfo();
                    $now_time = time();

                    if($return_user_data['vip_time']){
                        if($return_user_data['vip_time']>=$now_time){
                            $vip_time_status = 1;

                            $vip_time = date('Y-m-d H:i:s',$return_user_data['vip_time']);
                        }else{
                            $vip_time_status = 0;
                            $vip_time = 0;
                        }
                    }else{
                        $vip_time_status = 0;
                        $vip_time = 0;
                    }

                    $this->success("登录成功", ['http_result' => $json,'openid'=>$json['openid'],'token' =>$return_user_data['token'],'vip_time_status'=>$vip_time_status,'vip_time'=>$vip_time ]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败",$http_result['msg']);
            }
        }

        return;
    }

     /**
    * 获取个人信息 
    **/
    public function userInfo(){
        $user = $this->auth->getUser();
        $this->success('获取个人信息',$user->toArray());
    }

      /**
     * 修改用户信息
     * @param string $nickname 姓名
     * @param string $username 真实姓名
     * @param string $gender 性别男1女是0
     * @param string $mobile 手机号码
     * @param string $chehang_name 车行名称
     * @param string $region 归属地区
     * @param string $chehang_address 车行地址
     * @param string $id_img 身份证照片
     */
    public function edit(){
        $user = $this->auth->getUser();
        $params = input();
        $age = input('age');
        $nickname = input('nickname');
     
        if($age){
            $user->age = $age;
        }
        if($nickname){
            $user->nickname = $nickname;
        }
        if($params['username']){
            $user->username = $params['username'];
        }
        if($params['gender']){
            $user->gender = $params['gender'];
        }
        if($params['mobile']){
            $user->mobile = $params['mobile'];
        }
        if($params['chehang_name']){
            $user->chehang_name = $params['chehang_name'];
        }
        if($params['region']){
            $user->region = $params['region'];
        }
        if($params['chehang_address']){
            $user->chehang_address = $params['chehang_address'];
        }
        if($params['id_img']){
            $user->id_img = $params['id_img'];
        }
        $user->save();
        $this->success('修改成功');
    }
  
    /**
     * 获取我的求购列表
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_manuscript)
     */
    public function my_manuscript()
    {
        $user = $this->auth->getUser();
        $my_manuscript = Db::name('manuscript')->where(['user_id'=>$user->id])->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->order('createtime desc')->select();

        $this->success('获取我的求购列表',$my_manuscript);
    }

    /**
     * 获取我的车源列表
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_car)
     */
    public function my_car()
    {
        $user = $this->auth->getUser();
        $Car_Model = new Car_Model();
        $my_car = $Car_Model->where(['user_id'=>$user->id])->order('weigh desc')->select();

        $this->success('获取我的车源列表',$my_car);
    }

     /**
     * 获取我的邀请列表
     * @ApiSummary  (effect_num 有效邀请数量，总邀请数量 invitation_num 数组下面的jointime是加入时间)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_invite)
     */
    public function my_invite()
    {
        $user = $this->auth->getUser();
        if($user->tui_user_id){
            $return['tui_user_id_array'] = User_Model::all(['id','in',$user->tui_user_id]);            
        }
        $return['effect_num'] = $user->effect_num;
        $return['invitation_num'] = $user->invitation_num;

        $this->success('获取我的邀请列表',$return);
    }

    /**
     * 获取我的历史记录
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_history)
     */
    public function my_history()
    {
        $user = $this->auth->getUser();
        $Car_Model = new Car_Model();
        if($user->history){
            $history = rtrim($user->history,',');

            $return = $Car_Model->where('id','in',$history)->select();

        }else{
            $return = [];
        }
        
        $this->success('获取我的历史记录',$return);
    }



}
